from django import forms
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from PIL import Image

from app.common import get_default_timezone, get_timezone_list, parse_bool
from tinymce.widgets import TinyMCE

from settings.core import Tab


@Tab(_('General'), support_files=True)
class GeneralSettingsForm(forms.Form):
    SITE_NAME = forms.CharField(label=_('Site name'), max_length=40)
    LOGO = forms.ImageField(label=_('Logo'), required=False, help_text=_(
        'Recommanded size: 250px width, 100px height.'))
    SHOW_LOGO = forms.BooleanField(label=_('Show Logo'), help_text=_(
        'Show logo image instead of site name.'), required=False)
    TIMEZONE = forms.ChoiceField(choices=get_timezone_list(
    ), initial=get_default_timezone())
    DATETIME_FORMAT = forms.CharField(
        label=_('Datetime Format'), max_length=40, initial=settings.DATETIME_FORMAT, help_text=_('Available formats: <a href="https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#std:templatefilter-date" target="_blank">Learn More!</a>'))

    SEO_KEYWORDS = forms.CharField(label=_("SEO Keywords"), required=False, help_text=_("e.g. keyword1, keyword2, ...etc"))
    SEO_DESC = forms.CharField(label=_("SEO Description"), required=False, widget=forms.Textarea(attrs={"rows": 5}))

    HEAD_CODE = forms.CharField(label=_('Head code'), widget=forms.Textarea(attrs={'rows': 5}), help_text=_('e.g. Google Analytics, Facebook Pixel, custom CSS/JS...etc'), required=False)

    VALID_IPS = forms.CharField(label=_('Valid IPs'),
                                widget=forms.Textarea(attrs={'rows': 5}),
                                help_text=_('Used for custom domains DNS records!'), required=False)

    fields_types = {
        "SHOW_LOGO": parse_bool,
    }

    def clean(self):
        super().clean()

        # Change Logo resolution.
        if 'LOGO' in self.changed_data:
            # resize the logo image
            image = self.cleaned_data['LOGO']

            try:
                with Image.open(image) as img:
                    img.thumbnail(settings.LOGO_SIZE)
                    img.save(settings.LOGO_PATH)
                    image.name = settings.LOGO_PATH
            except IOError as e:
                print(f"IOError: {e}")


@Tab(_('Email (SMTP)'))
class EmailSettingsForm(forms.Form):
    ENCRYPTION = (
        ('TLS', 'TLS'),
        ('SSL', 'SSL')
    )

    SMTP_HOST = forms.CharField(label=_('SMTP HOST'), max_length=64)
    SMTP_PORT = forms.IntegerField(label=_('SMTP PORT'))
    SMTP_USER = forms.EmailField(label=_('SMTP USERNAME'), max_length=64, help_text=_(
        'This email address will receive messages from "Contact Us" page!'))
    SMTP_PASS = forms.CharField(label=_('SMTP PASSWORD'), max_length=64)
    MAIL_ENCRYPTION = forms.ChoiceField(choices=ENCRYPTION)

    fields_types = {
        "SMTP_PORT": int
    }


@Tab(_('Email Templates'))
class EmailsTemplates(forms.Form):
    EMAIL_HEADER = forms.CharField(widget=TinyMCE(mce_attrs={'height': '150px'}),
                                   label=_('Email Header template (will be included in every email template).'), help_text=_("""Valid placeholders: <b>{{ SITE_NAME }}</b>"""))
    EMAIL_FOOTER = forms.CharField(widget=TinyMCE(mce_attrs={'height': '150px'}),
                                   label=_('Email Footer template (will be included in every email template).'))

    EMAIL_NEW_ACCOUNT = forms.CharField(widget=TinyMCE(mce_attrs={'height': '300px'}),
                                        label=_('Email template for a new acoount registration.'), help_text=_("""Valid placeholders: <b>{{ SITE_NAME }}
{{ USER_USERNAME }}
{{ USER_EMAIL }}
{{ USER_TOKEN }}
{{ ACCOUNT_ACTIVATION_LINK }}</b>"""))

    EMAIL_RESET_PASSWORD = forms.CharField(widget=TinyMCE(mce_attrs={'height': '300px'}),
                                           label=_('Email template for password reset.'), help_text=_("""Valid placeholders: <b>{{ SITE_NAME }}
{{ USER_USERNAME }}
{{ USER_EMAIL }}
{{ USER_TOKEN }}
{{ RESET_PASSWORD_LINK }}</b>"""))


@Tab(_('Contact Settings'))
class ContactSettingsForm(forms.Form):
    CONTACT_MESSAGE = forms.CharField(
        label=_('Description for visitors'), widget=forms.Textarea(attrs={'rows': 5}), required=False)
    CONTACT_PHONE = forms.CharField(label=_('Phone number'), required=False)
    CONTACT_TELEPHONE = forms.CharField(
        label=_('Telephone number'), required=False)
    CONTACT_EMAIL = forms.CharField(label=_('Contact Email'), required=False)
    CONTACT_LOCATION = forms.CharField(
        label=_('Address / location'), required=False)
    CONTACT_MAP = forms.CharField(
        label=_('Map (iframe)'), widget=forms.Textarea(attrs={'rows': 5}), required=False)


@Tab(_('Initial Values'))
class InitialValuesForm(forms.Form):
    SHOW_INITIAL_VALUES = forms.BooleanField(
        label=_('Show initial values!'), required=False, help_text=_('Show the below values on the "Home" page!'))
    TOTAL_USERS = forms.IntegerField(label=_('Total users'), required=False)
    TOTAL_LINKS = forms.IntegerField(label=_('Total links'), required=False)
    TOTAL_CLICKS = forms.IntegerField(
        label=_('Total clicks'), required=False)
    TOTAL_DOMAINS = forms.IntegerField(
        label=_('Total domains'), required=False)

    fields_types = {
        'SHOW_INITIAL_VALUES': parse_bool,
    }
